import { STORAGE_KEYS, PRESET_DATA_IDS } from '@/constants/storage';
import { storageService } from '@/services/storage';
import type { OperationResult } from '@/types/common/base';
import type { 
  ICourseCategory, 
  ICourseCategoryCreateRequest, 
  ICourseCategoryUpdateRequest, 
  ICourseCategoryQueryParams,
  ICourseCategoryTreeNode,
  ICourseCategoryStatistics,
  ICourseCategorySummary,
  IPresetCourseCategory
} from '@/types/course/courseCategory';
import { CourseCategoryStatusEnum, PresetCourseCategoryEnum, PresetCourseCategoryText } from '@/types/course/enums';

/**
 * 课程分类验证结果接口
 */
interface ICourseCategoryValidationResult {
  /** 是否验证通过 */
  isValid: boolean;
  /** 错误信息列表 */
  errors: string[];
}

/**
 * 课程分类服务类
 * @description 负责课程分类数据的增删改查和业务逻辑处理
 */
export class CourseCategoryService {
  /**
   * 初始化预设分类
   * @returns 操作结果
   */
  async initializePresetCategories(): Promise<OperationResult<ICourseCategory[]>> {
    try {
      const existingCategoriesResult = await this.getAllCategories();
      if (!existingCategoriesResult.success) {
        return existingCategoriesResult;
      }

      const existingCategories = existingCategoriesResult.data;
      const presetCategories = this.getPresetCategories();
      const categoriesToCreate: ICourseCategory[] = [];

      for (const presetCategory of presetCategories) {
        // 检查预设分类是否已存在
        const exists = existingCategories.some(cat => 
          cat.categoryCode === presetCategory.categoryCode && cat.isPreset
        );

        if (!exists) {
          const now = Date.now();
          const newCategory: ICourseCategory = {
            id: `${PRESET_DATA_IDS.COURSE_CATEGORY_PREFIX}${presetCategory.categoryCode}`,
            ...presetCategory,
            status: CourseCategoryStatusEnum.ACTIVE,
            parentId: undefined,
            level: 1,
            path: presetCategory.name,
            isPreset: true,
            deletable: false,
            createdAt: now,
            updatedAt: now
          };
          categoriesToCreate.push(newCategory);
        }
      }

      if (categoriesToCreate.length > 0) {
        const allCategories = [...existingCategories, ...categoriesToCreate];
        const saveResult = await storageService.setItem(STORAGE_KEYS.COURSE_CATEGORIES, allCategories);
        
        if (!saveResult.success) {
          return saveResult;
        }
      }

      return {
        success: true,
        data: categoriesToCreate
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '初始化预设分类失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取所有课程分类
   * @param queryParams 查询参数
   * @returns 分类列表
   */
  async getAllCategories(queryParams?: ICourseCategoryQueryParams): Promise<OperationResult<ICourseCategory[]>> {
    try {
      const result = await storageService.getItem<ICourseCategory[]>(STORAGE_KEYS.COURSE_CATEGORIES);
      
      if (!result.success) {
        // 如果没有数据，初始化预设分类
        if (result.errorCode === 'INVALID_DATA_FORMAT') {
          const initResult = await this.initializePresetCategories();
          if (initResult.success) {
            return this.getAllCategories(queryParams);
          }
          return {
            success: true,
            data: []
          };
        }
        return result;
      }

      let categories = result.data || [];

      // 过滤已删除的分类
      categories = categories.filter(category => category.status !== CourseCategoryStatusEnum.DELETED);

      // 应用查询参数
      if (queryParams) {
        categories = this.filterCategories(categories, queryParams);
      }

      // 按排序权重和名称排序
      categories.sort((a, b) => {
        if (a.sortOrder !== b.sortOrder) {
          return a.sortOrder - b.sortOrder;
        }
        return a.name.localeCompare(b.name);
      });

      return {
        success: true,
        data: categories
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程分类列表失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据ID获取课程分类
   * @param id 分类ID
   * @returns 分类信息
   */
  async getCategoryById(id: string): Promise<OperationResult<ICourseCategory>> {
    try {
      const categoriesResult = await this.getAllCategories();
      if (!categoriesResult.success) {
        return categoriesResult;
      }

      const category = categoriesResult.data.find(c => c.id === id);
      if (!category) {
        return {
          success: false,
          error: '课程分类不存在'
        };
      }

      return {
        success: true,
        data: category
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程分类信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据分类代码获取课程分类
   * @param categoryCode 分类代码
   * @returns 分类信息
   */
  async getCategoryByCategoryCode(categoryCode: string): Promise<OperationResult<ICourseCategory>> {
    try {
      const categoriesResult = await this.getAllCategories();
      if (!categoriesResult.success) {
        return categoriesResult;
      }

      const category = categoriesResult.data.find(c => c.categoryCode === categoryCode);
      if (!category) {
        return {
          success: false,
          error: '课程分类不存在'
        };
      }

      return {
        success: true,
        data: category
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程分类信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取分类树结构
   * @param parentId 父分类ID（可选，获取指定父分类下的子树）
   * @returns 分类树
   */
  async getCategoryTree(parentId?: string): Promise<OperationResult<ICourseCategoryTreeNode[]>> {
    try {
      const categoriesResult = await this.getAllCategories();
      if (!categoriesResult.success) {
        return categoriesResult;
      }

      const categories = categoriesResult.data;
      
      // 获取课程数量统计
      const courseCountMap = await this.getCategoryCourseCountMap();

      // 构建树结构
      const tree = this.buildCategoryTree(categories, courseCountMap, parentId);

      return {
        success: true,
        data: tree
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取分类树结构失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 创建课程分类
   * @param categoryData 分类数据
   * @returns 创建的分类信息
   */
  async createCategory(categoryData: ICourseCategoryCreateRequest): Promise<OperationResult<ICourseCategory>> {
    try {
      // 数据验证
      const validationResult = this.validateCategoryData(categoryData);
      if (!validationResult.isValid) {
        return {
          success: false,
          error: validationResult.errors.join('; ')
        };
      }

      // 检查分类代码是否已存在
      const existingCategoryResult = await this.getCategoryByCategoryCode(categoryData.categoryCode);
      if (existingCategoryResult.success) {
        return {
          success: false,
          error: `分类代码 ${categoryData.categoryCode} 已存在`
        };
      }

      // 验证父分类是否存在
      let parentCategory: ICourseCategory | undefined;
      if (categoryData.parentId) {
        const parentResult = await this.getCategoryById(categoryData.parentId);
        if (!parentResult.success) {
          return {
            success: false,
            error: '父分类不存在'
          };
        }
        parentCategory = parentResult.data;
      }

      // 获取现有分类列表
      const categoriesResult = await this.getAllCategories();
      if (!categoriesResult.success) {
        return categoriesResult;
      }

      const categories = categoriesResult.data;

      // 计算层级和路径
      const level = parentCategory ? parentCategory.level + 1 : 1;
      const path = parentCategory ? `${parentCategory.path} > ${categoryData.name}` : categoryData.name;

      // 创建新分类对象
      const now = Date.now();
      const newCategory: ICourseCategory = {
        id: this.generateCategoryId(),
        ...categoryData,
        level,
        path,
        status: categoryData.status || CourseCategoryStatusEnum.ACTIVE,
        color: categoryData.color || this.generateRandomColor(),
        isPreset: false,
        deletable: true,
        createdAt: now,
        updatedAt: now
      };

      // 添加到分类列表
      categories.push(newCategory);

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.COURSE_CATEGORIES, categories, {
        createBackup: true
      });

      if (!saveResult.success) {
        return saveResult;
      }

      return {
        success: true,
        data: newCategory
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '创建课程分类失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 更新课程分类信息
   * @param id 分类ID
   * @param updateData 更新数据
   * @returns 更新后的分类信息
   */
  async updateCategory(id: string, updateData: Omit<ICourseCategoryUpdateRequest, 'id'>): Promise<OperationResult<ICourseCategory>> {
    try {
      // 获取现有分类列表
      const categoriesResult = await this.getAllCategories();
      if (!categoriesResult.success) {
        return categoriesResult;
      }

      const categories = categoriesResult.data;
      const categoryIndex = categories.findIndex(c => c.id === id);

      if (categoryIndex === -1) {
        return {
          success: false,
          error: '课程分类不存在'
        };
      }

      const existingCategory = categories[categoryIndex];

      // 检查是否为预设分类且尝试修改不可修改的字段
      if (existingCategory.isPreset) {
        if (updateData.categoryCode && updateData.categoryCode !== existingCategory.categoryCode) {
          return {
            success: false,
            error: '预设分类的分类代码不能修改'
          };
        }
        if (updateData.isPreset === false) {
          return {
            success: false,
            error: '不能修改预设分类的预设标识'
          };
        }
      }

      // 如果更新分类代码，检查新代码是否已存在
      if (updateData.categoryCode && updateData.categoryCode !== existingCategory.categoryCode) {
        const existingCategoryResult = await this.getCategoryByCategoryCode(updateData.categoryCode);
        if (existingCategoryResult.success) {
          return {
            success: false,
            error: `分类代码 ${updateData.categoryCode} 已存在`
          };
        }
      }

      // 验证父分类是否存在（如果有更新）
      let parentCategory: ICourseCategory | undefined;
      if (updateData.parentId !== undefined) {
        if (updateData.parentId) {
          const parentResult = await this.getCategoryById(updateData.parentId);
          if (!parentResult.success) {
            return {
              success: false,
              error: '父分类不存在'
            };
          }
          parentCategory = parentResult.data;

          // 检查是否会形成循环引用
          if (this.wouldCreateCircularReference(id, updateData.parentId, categories)) {
            return {
              success: false,
              error: '不能将分类设置为自己的子分类'
            };
          }
        }
      } else {
        // 如果没有更新父分类，使用现有的父分类
        if (existingCategory.parentId) {
          const parentResult = await this.getCategoryById(existingCategory.parentId);
          if (parentResult.success) {
            parentCategory = parentResult.data;
          }
        }
      }

      // 计算新的层级和路径
      let level = existingCategory.level;
      let path = existingCategory.path;

      if (updateData.parentId !== undefined || updateData.name) {
        const newParentId = updateData.parentId !== undefined ? updateData.parentId : existingCategory.parentId;
        const newName = updateData.name || existingCategory.name;
        
        level = parentCategory ? parentCategory.level + 1 : 1;
        path = parentCategory ? `${parentCategory.path} > ${newName}` : newName;
      }

      // 合并更新数据
      const updatedCategory: ICourseCategory = {
        ...existingCategory,
        ...updateData,
        id, // 确保ID不被修改
        level,
        path,
        updatedAt: Date.now()
      };

      // 验证更新后的数据
      const validationResult = this.validateCategoryData(updatedCategory);
      if (!validationResult.isValid) {
        return {
          success: false,
          error: validationResult.errors.join('; ')
        };
      }

      // 更新分类列表
      categories[categoryIndex] = updatedCategory;

      // 如果更新了父分类或名称，需要更新所有子分类的路径
      if (updateData.parentId !== undefined || updateData.name) {
        this.updateChildrenPaths(categories, updatedCategory);
      }

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.COURSE_CATEGORIES, categories, {
        createBackup: true
      });

      if (!saveResult.success) {
        return saveResult;
      }

      return {
        success: true,
        data: updatedCategory
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新课程分类信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 删除课程分类（软删除）
   * @param id 分类ID
   * @returns 操作结果
   */
  async deleteCategory(id: string): Promise<OperationResult<void>> {
    try {
      const categoryResult = await this.getCategoryById(id);
      if (!categoryResult.success) {
        return categoryResult;
      }

      const category = categoryResult.data;

      // 检查是否为预设分类
      if (category.isPreset) {
        return {
          success: false,
          error: '预设分类不能删除'
        };
      }

      // 检查是否不允许删除
      if (!category.deletable) {
        return {
          success: false,
          error: '该分类不允许删除'
        };
      }

      // 检查是否有子分类
      const hasChildrenResult = await this.checkCategoryHasChildren(id);
      if (!hasChildrenResult.success) {
        return hasChildrenResult;
      }

      if (hasChildrenResult.data) {
        return {
          success: false,
          error: '该分类下有子分类，请先删除子分类'
        };
      }

      // 检查是否有关联的课程
      const hasCoursesResult = await this.checkCategoryHasCourses(id);
      if (!hasCoursesResult.success) {
        return hasCoursesResult;
      }

      if (hasCoursesResult.data) {
        return {
          success: false,
          error: '该分类下有关联的课程，请先处理相关课程'
        };
      }

      // 软删除：将状态设置为已删除
      const updateResult = await this.updateCategory(id, {
        status: CourseCategoryStatusEnum.DELETED
      });

      if (!updateResult.success) {
        return updateResult;
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '删除课程分类失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 批量删除课程分类
   * @param ids 分类ID列表
   * @returns 操作结果
   */
  async batchDeleteCategories(ids: string[]): Promise<OperationResult<{ successCount: number; failedCount: number; errors: string[] }>> {
    try {
      let successCount = 0;
      let failedCount = 0;
      const errors: string[] = [];

      for (const id of ids) {
        const result = await this.deleteCategory(id);
        if (result.success) {
          successCount++;
        } else {
          failedCount++;
          errors.push(`分类 ${id}: ${result.error}`);
        }
      }

      return {
        success: true,
        data: {
          successCount,
          failedCount,
          errors
        }
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '批量删除课程分类失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取课程分类统计信息
   * @returns 统计信息
   */
  async getCategoryStatistics(): Promise<OperationResult<ICourseCategoryStatistics>> {
    try {
      const categoriesResult = await this.getAllCategories();
      if (!categoriesResult.success) {
        return categoriesResult;
      }

      const categories = categoriesResult.data;

      // 基础统计
      const totalCount = categories.length;
      const activeCount = categories.filter(c => c.status === CourseCategoryStatusEnum.ACTIVE).length;
      const disabledCount = categories.filter(c => c.status === CourseCategoryStatusEnum.DISABLED).length;
      const presetCount = categories.filter(c => c.isPreset).length;
      const customCount = categories.filter(c => !c.isPreset).length;

      // 层级分布统计
      const levelMap = new Map<number, number>();
      categories.forEach(category => {
        levelMap.set(category.level, (levelMap.get(category.level) || 0) + 1);
      });
      const levelDistribution = Array.from(levelMap.entries()).map(([level, count]) => ({
        level,
        count
      }));

      // 使用情况统计
      const courseCountMap = await this.getCategoryCourseCountMap();
      const usageDistribution = categories.map(category => ({
        categoryId: category.id,
        categoryName: category.name,
        courseCount: courseCountMap.get(category.id) || 0
      }));

      const statistics: ICourseCategoryStatistics = {
        totalCount,
        activeCount,
        disabledCount,
        presetCount,
        customCount,
        levelDistribution,
        usageDistribution
      };

      return {
        success: true,
        data: statistics
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程分类统计信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取课程分类简要信息列表
   * @param queryParams 查询参数
   * @returns 分类简要信息列表
   */
  async getCategorySummaries(queryParams?: ICourseCategoryQueryParams): Promise<OperationResult<ICourseCategorySummary[]>> {
    try {
      const categoriesResult = await this.getAllCategories(queryParams);
      if (!categoriesResult.success) {
        return categoriesResult;
      }

      const courseCountMap = await this.getCategoryCourseCountMap();

      const summaries: ICourseCategorySummary[] = categoriesResult.data.map(category => ({
        id: category.id,
        name: category.name,
        categoryCode: category.categoryCode,
        color: category.color,
        icon: category.icon,
        parentId: category.parentId,
        level: category.level,
        path: category.path,
        status: category.status,
        courseCount: courseCountMap.get(category.id) || 0
      }));

      return {
        success: true,
        data: summaries
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程分类简要信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 搜索课程分类
   * @param keyword 搜索关键词
   * @param limit 结果数量限制
   * @returns 搜索结果
   */
  async searchCategories(keyword: string, limit: number = 10): Promise<OperationResult<ICourseCategory[]>> {
    try {
      if (!keyword.trim()) {
        return {
          success: true,
          data: []
        };
      }

      const categoriesResult = await this.getAllCategories();
      if (!categoriesResult.success) {
        return categoriesResult;
      }

      const categories = categoriesResult.data;
      const lowerKeyword = keyword.toLowerCase();

      const matchedCategories = categories.filter(category => 
        category.name.toLowerCase().includes(lowerKeyword) ||
        category.categoryCode.toLowerCase().includes(lowerKeyword) ||
        (category.description && category.description.toLowerCase().includes(lowerKeyword)) ||
        (category.tags && category.tags.some(tag => tag.toLowerCase().includes(lowerKeyword)))
      );

      // 按相关性排序（分类名称匹配优先）
      matchedCategories.sort((a, b) => {
        const aNameMatch = a.name.toLowerCase().includes(lowerKeyword);
        const bNameMatch = b.name.toLowerCase().includes(lowerKeyword);
        
        if (aNameMatch && !bNameMatch) return -1;
        if (!aNameMatch && bNameMatch) return 1;
        
        return a.name.localeCompare(b.name);
      });

      return {
        success: true,
        data: matchedCategories.slice(0, limit)
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '搜索课程分类失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取预设分类配置
   * @returns 预设分类列表
   */
  private getPresetCategories(): IPresetCourseCategory[] {
    return [
      {
        name: PresetCourseCategoryText[PresetCourseCategoryEnum.PRIMARY_SCHOOL],
        categoryCode: PresetCourseCategoryEnum.PRIMARY_SCHOOL,
        description: '小学阶段的基础学科课程',
        color: '#1890ff',
        icon: 'book',
        sortOrder: 1,
        tags: ['小学', '基础教育', '学科课程']
      },
      {
        name: PresetCourseCategoryText[PresetCourseCategoryEnum.PRIMARY_CLUB],
        categoryCode: PresetCourseCategoryEnum.PRIMARY_CLUB,
        description: '小学校内的社团活动课程',
        color: '#52c41a',
        icon: 'team',
        sortOrder: 2,
        tags: ['小学', '社团', '兴趣培养']
      },
      {
        name: PresetCourseCategoryText[PresetCourseCategoryEnum.YOUTH_PALACE],
        categoryCode: PresetCourseCategoryEnum.YOUTH_PALACE,
        description: '少年宫提供的各类兴趣课程',
        color: '#faad14',
        icon: 'crown',
        sortOrder: 3,
        tags: ['少年宫', '兴趣课程', '艺术']
      },
      {
        name: PresetCourseCategoryText[PresetCourseCategoryEnum.TRAINING_INSTITUTION],
        categoryCode: PresetCourseCategoryEnum.TRAINING_INSTITUTION,
        description: '培训机构提供的专业课程',
        color: '#f5222d',
        icon: 'bank',
        sortOrder: 4,
        tags: ['培训机构', '专业培训', '技能提升']
      },
      {
        name: PresetCourseCategoryText[PresetCourseCategoryEnum.HOME_TUTORING],
        categoryCode: PresetCourseCategoryEnum.HOME_TUTORING,
        description: '家庭辅导和一对一教学课程',
        color: '#722ed1',
        icon: 'home',
        sortOrder: 5,
        tags: ['家庭辅导', '一对一', '个性化教学']
      },
      {
        name: PresetCourseCategoryText[PresetCourseCategoryEnum.EXTRACURRICULAR_CLUB],
        categoryCode: PresetCourseCategoryEnum.EXTRACURRICULAR_CLUB,
        description: '课外社团和兴趣小组课程',
        color: '#13c2c2',
        icon: 'star',
        sortOrder: 6,
        tags: ['课外活动', '社团', '兴趣小组']
      }
    ];
  }

  /**
   * 验证分类数据
   * @param categoryData 分类数据
   * @returns 验证结果
   */
  private validateCategoryData(categoryData: Partial<ICourseCategory>): ICourseCategoryValidationResult {
    const errors: string[] = [];

    // 必填字段验证
    if (!categoryData.name || !categoryData.name.trim()) {
      errors.push('分类名称不能为空');
    }

    if (!categoryData.categoryCode || !categoryData.categoryCode.trim()) {
      errors.push('分类代码不能为空');
    }

    // 格式验证
    if (categoryData.name && categoryData.name.length > 50) {
      errors.push('分类名称长度不能超过50个字符');
    }

    if (categoryData.categoryCode && categoryData.categoryCode.length > 30) {
      errors.push('分类代码长度不能超过30个字符');
    }

    if (categoryData.sortOrder && (categoryData.sortOrder < 0 || categoryData.sortOrder > 9999)) {
      errors.push('排序权重必须在0-9999之间');
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  }

  /**
   * 过滤分类列表
   * @param categories 分类列表
   * @param queryParams 查询参数
   * @returns 过滤后的分类列表
   */
  private filterCategories(categories: ICourseCategory[], queryParams: ICourseCategoryQueryParams): ICourseCategory[] {
    return categories.filter(category => {
      // 分类名称模糊搜索
      if (queryParams.name && !category.name.toLowerCase().includes(queryParams.name.toLowerCase())) {
        return false;
      }

      // 分类代码精确匹配
      if (queryParams.categoryCode && category.categoryCode !== queryParams.categoryCode) {
        return false;
      }

      // 父分类匹配
      if (queryParams.parentId !== undefined && category.parentId !== queryParams.parentId) {
        return false;
      }

      // 状态匹配
      if (queryParams.status && category.status !== queryParams.status) {
        return false;
      }

      // 层级匹配
      if (queryParams.level && category.level !== queryParams.level) {
        return false;
      }

      // 预设分类匹配
      if (queryParams.isPreset !== undefined && category.isPreset !== queryParams.isPreset) {
        return false;
      }

      // 可删除性匹配
      if (queryParams.deletable !== undefined && category.deletable !== queryParams.deletable) {
        return false;
      }

      // 标签匹配
      if (queryParams.tags && queryParams.tags.length > 0) {
        const hasMatchingTag = queryParams.tags.some(tag => 
          category.tags && category.tags.includes(tag)
        );
        if (!hasMatchingTag) {
          return false;
        }
      }

      return true;
    });
  }

  /**
   * 构建分类树结构
   * @param categories 分类列表
   * @param courseCountMap 课程数量映射
   * @param parentId 父分类ID
   * @returns 分类树节点列表
   */
  private buildCategoryTree(
    categories: ICourseCategory[], 
    courseCountMap: Map<string, number>, 
    parentId?: string
  ): ICourseCategoryTreeNode[] {
    const nodes: ICourseCategoryTreeNode[] = [];

    // 找到指定父分类下的直接子分类
    const childCategories = categories.filter(cat => cat.parentId === parentId);

    for (const category of childCategories) {
      const node: ICourseCategoryTreeNode = {
        ...category,
        courseCount: courseCountMap.get(category.id) || 0,
        children: this.buildCategoryTree(categories, courseCountMap, category.id),
        expanded: false,
        selectable: true,
        disabled: category.status !== CourseCategoryStatusEnum.ACTIVE
      };

      nodes.push(node);
    }

    return nodes;
  }

  /**
   * 获取分类课程数量映射
   * @returns 分类ID到课程数量的映射
   */
  private async getCategoryCourseCountMap(): Promise<Map<string, number>> {
    const courseCountMap = new Map<string, number>();

    try {
      const coursesResult = await storageService.getItem(STORAGE_KEYS.COURSES);
      if (!coursesResult.success || !coursesResult.data) {
        return courseCountMap;
      }

      const courses = Array.isArray(coursesResult.data) ? coursesResult.data : [];
      
      courses.forEach((course: any) => {
        if (course.categoryIds && Array.isArray(course.categoryIds)) {
          course.categoryIds.forEach((categoryId: string) => {
            courseCountMap.set(categoryId, (courseCountMap.get(categoryId) || 0) + 1);
          });
        }
      });

    } catch (error) {
      console.warn('获取课程数量统计失败:', error);
    }

    return courseCountMap;
  }

  /**
   * 检查分类是否有子分类
   * @param categoryId 分类ID
   * @returns 检查结果
   */
  private async checkCategoryHasChildren(categoryId: string): Promise<OperationResult<boolean>> {
    try {
      const categoriesResult = await this.getAllCategories();
      if (!categoriesResult.success) {
        return categoriesResult;
      }

      const hasChildren = categoriesResult.data.some(cat => cat.parentId === categoryId);

      return {
        success: true,
        data: hasChildren
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '检查子分类失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 检查分类是否有关联的课程
   * @param categoryId 分类ID
   * @returns 检查结果
   */
  private async checkCategoryHasCourses(categoryId: string): Promise<OperationResult<boolean>> {
    try {
      const coursesResult = await storageService.getItem(STORAGE_KEYS.COURSES);
      if (!coursesResult.success || !coursesResult.data) {
        return {
          success: true,
          data: false
        };
      }

      const courses = Array.isArray(coursesResult.data) ? coursesResult.data : [];
      const hasCourses = courses.some((course: any) => 
        course.categoryIds && course.categoryIds.includes(categoryId)
      );

      return {
        success: true,
        data: hasCourses
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '检查关联课程失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 检查是否会形成循环引用
   * @param categoryId 分类ID
   * @param newParentId 新父分类ID
   * @param categories 所有分类
   * @returns 是否会形成循环引用
   */
  private wouldCreateCircularReference(categoryId: string, newParentId: string, categories: ICourseCategory[]): boolean {
    if (categoryId === newParentId) {
      return true;
    }

    // 检查新父分类的祖先链中是否包含当前分类
    let currentParentId = newParentId;
    const visited = new Set<string>();

    while (currentParentId && !visited.has(currentParentId)) {
      visited.add(currentParentId);
      
      if (currentParentId === categoryId) {
        return true;
      }

      const parentCategory = categories.find(cat => cat.id === currentParentId);
      currentParentId = parentCategory?.parentId || '';
    }

    return false;
  }

  /**
   * 更新子分类的路径
   * @param categories 所有分类
   * @param parentCategory 父分类
   */
  private updateChildrenPaths(categories: ICourseCategory[], parentCategory: ICourseCategory): void {
    const children = categories.filter(cat => cat.parentId === parentCategory.id);
    
    for (const child of children) {
      child.level = parentCategory.level + 1;
      child.path = `${parentCategory.path} > ${child.name}`;
      child.updatedAt = Date.now();
      
      // 递归更新子分类的子分类
      this.updateChildrenPaths(categories, child);
    }
  }

  /**
   * 生成随机颜色
   * @returns 颜色值
   */
  private generateRandomColor(): string {
    const colors = [
      '#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1',
      '#13c2c2', '#eb2f96', '#fa541c', '#a0d911', '#2f54eb'
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  }

  /**
   * 生成分类ID
   * @returns 分类ID
   */
  private generateCategoryId(): string {
    const timestamp = Date.now().toString(36);
    const randomStr = Math.random().toString(36).substr(2, 9);
    return `category_${timestamp}_${randomStr}`;
  }
}

/**
 * 默认课程分类服务实例
 */
export const courseCategoryService = new CourseCategoryService();